#pragma once

#include"Socket.hpp"
#include<signal.h>
#include<functional>

using func_t = std::function<std::string(std::string&)>;

class TcpServer
{
public:
    TcpServer(uint16_t port,func_t callback)
        :_port(port)
        ,_callback(callback)
    {}

    ~TcpServer()
    {}

    void InitServer()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        std::cout << "server init success... " << std::endl;
    }

    void Start()
    {
        signal(SIGCHLD,SIG_IGN);
        signal(SIGPIPE,SIG_IGN);
        while(1)
        {
            uint16_t clientport;
            std::string clientip;
            int sockfd = _listensock.Accept(&clientport,&clientip);
            if(sockfd < 0 )
            {
                continue;
            }
            std::cout << "accept a new link,sockfd:" << sockfd <<  " ,clientport:" << clientport << " ,clientip" << clientip << std::endl;
            
            //多进程
            if(fork() == 0)
            {
                _listensock.Close();
                std::string inbuff_stream;
                while(1)
                {
                    char buffer[1024];
                    ssize_t n = read(sockfd,buffer,sizeof(buffer));
                    //计算
                    if(n > 0)
                    {
                        buffer[n] = 0;
                        inbuff_stream += buffer;
                        std::cout << inbuff_stream;

                        std::string info = _callback(inbuff_stream);
                        //std::cout << info << std::endl;
                        if(info.empty())    continue;

                        
                        write(sockfd,info.c_str(),info.size());
                    }
                    else if(n == 0)    break;
                    else break;
                }
                exit(0);
            }

            //父进程
            close(sockfd);
        }

    }

private:
    Sock _listensock;
    uint16_t _port;
    func_t _callback;
};